<template>
  <div class="app-container">
    <el-form ref="formRef" :model="formData" :rules="rules" label-width="120px" class="proposal-form">
      <el-card class="mb-3">
        <template #header>
          <div class="card-header">
            <span>基本信息</span>
          </div>
        </template>
        <el-row :gutter="20">
          <!-- 状态 -->
          <el-col :span="12">
            <el-form-item label="状态" prop="status">
              <el-input v-model="formData.status" disabled></el-input>
            </el-form-item>
          </el-col>
          <!-- 月份 -->
          <el-col :span="12">
            <el-form-item label="月份" prop="month">
              <el-date-picker v-model="formData.month" type="month" style="width: 100%;" placeholder="请选择月份" value-format="YYYY-MM" ></el-date-picker>
            </el-form-item>
          </el-col>
          <!-- 部门 -->
          <el-col :span="12">
            <el-form-item label="部门" prop="departmentName">
              <el-select v-model="formData.departmentName" style="width: 100%;" >
                <el-option v-for="dept in departments" :key="dept.value" :label="dept.label":value="dept.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <!-- 提案人姓名 -->
          <el-col :span="12">
            <el-form-item label="提案人姓名" prop="proposerName">
              <el-input v-model="formData.proposerName"></el-input>
            </el-form-item>
          </el-col>
          <!-- 提案人ID -->
          <el-col :span="12">
            <el-form-item label="提案人ID" prop="proposerId">
              <el-input v-model="formData.proposerId"></el-input>
            </el-form-item>
          </el-col>
          <!-- 提案时间 -->
          <el-col :span="12">
            <el-form-item label="提案时间" prop="proposalTime">
              <el-date-picker v-model="formData.proposalTime" type="date" style="width: 100%;"></el-date-picker>
            </el-form-item>
          </el-col>
          <!-- 提案类型 -->
          <el-col :span="12">
            <el-form-item label="提案类型" prop="proposalTypeName">
              <el-select v-model="formData.proposalTypeName" @change="typeChange" style="width: 100%;">
                <el-option v-for="item in proposalTypes" :key="item.type" :label="item.label" :value="item.type"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <!-- 提案名称 -->
          <el-col :span="12">
            <el-form-item label="提案名称" prop="title">
              <el-input v-model="formData.title"></el-input>
            </el-form-item>
          </el-col>
          <!-- 提案类别 -->
          <el-col :span="12">
            <el-form-item label="提案类别" prop="categoryName">
              <el-select v-model="formData.categoryName" :disabled="!formData.proposalTypeName" style="width: 100%;">
                <el-option v-for="item in filteredCategories" :key="item" :label="item" :value="item"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <!-- 提案内容 -->
          <el-col :span="24">
            <el-form-item label="提案内容" prop="content">
              <el-input 
                type="textarea" 
                v-model="formData.content" 
                :rows="4" 
                placeholder="请输入提案的详细内容,包括问题描述、解决方案等,以及改善前后的对比图片.当涉及成本节省的情况,请提供具体的料号">
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-card>

      <el-card class="mb-3">
        <template #header>
          <div class="card-header">
            <span>推进信息</span>
          </div>
        </template>
        <el-row :gutter="20">
          <!-- 是否公司推进 -->
          <el-col :span="8">
            <el-form-item label="是否公司推进" prop="isCompanyPromoted">
              <el-radio-group v-model="formData.isCompanyPromoted">
                <el-radio :label="true">是</el-radio>
                <el-radio :label="false">否</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <!-- 是否需要财务介入 -->
          <el-col :span="8">
            <el-form-item label="是否需要财务介入" prop="isFinancePromoted">
              <el-radio-group v-model="formData.isFinancePromoted">
                <el-radio :label="true">是</el-radio>
                <el-radio :label="false">否</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <!-- 是否需要质量介入 -->
          <el-col :span="8">
            <el-form-item label="是否需要质量介入" prop="isQualityPromoted">
              <el-radio-group v-model="formData.isQualityPromoted">
                <el-radio :label="true">是</el-radio>
                <el-radio :label="false">否</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
      </el-card>
     
  

      <el-card class="mb-3">
        <template #header>
          <div class="card-header">
            <span>实施信息</span>
          </div>
        </template>
        <el-row :gutter="20">
          <!-- 实施部门 -->
          <el-col :span="12">
            <el-form-item label="实施部门" prop="implementationDepartment">
              <el-select v-model="formData.implementationDepartment" style="width: 100%;" >
                <el-option v-for="dept in departments" :key="dept.value" :label="dept.label" :value="dept.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <!-- 实施开始时间 -->
          <el-col :span="12">
            <el-form-item label="开始时间" prop="implementationStartTime">
              <el-date-picker v-model="formData.implementationStartTime" type="date" style="width: 100%;" value-format="YYYY-MM-DD"></el-date-picker>
            </el-form-item>
          </el-col>
          <!-- 实施结束时间 -->
          <el-col :span="12">
            <el-form-item label="结束时间" prop="implementationEndTime">
              <el-date-picker v-model="formData.implementationEndTime" type="date" style="width: 100%;" value-format="YYYY-MM-DD"></el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 实施人信息 -->
        <el-row :gutter="20">
          <el-col :span="12" v-for="i in 5" :key="i">
            <el-row :gutter="10">
              <el-col :span="12">
                <el-form-item :prop="'implementer' + i + 'Name'" :label="'实施人员' + i">
                  <el-input v-model="formData['implementer' + i + 'Name']" placeholder="姓名"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item :prop="'implementer' + i + 'EmployeeId'" label="工号">
                  <el-input v-model="formData['implementer' + i + 'EmployeeId']" placeholder="工号"></el-input>
                </el-form-item>
              </el-col>
            </el-row>
          </el-col>
        </el-row>
      </el-card>

      <el-card class="mb-3">
        <template #header>
          <div class="card-header">
            <span>其他信息</span>
          </div>
        </template>
        <el-row :gutter="20">
          <!-- 备注 -->
          <el-col :span="24">
            <el-form-item label="备注" prop="notes">
              <el-input type="textarea" v-model="formData.notes" :rows="3"></el-input>
            </el-form-item>
          </el-col>
          <!-- 图片上传 -->
          <el-col :span="24">
            <el-form-item label="相关图片">
              <div class="image-upload-container">
                <el-upload
                  class="image-uploader"
                  :action="uploadUrl"
                  :on-success="handleUploadSuccess"
                  :on-error="handleUploadError"
                  :on-remove="handleRemove"
                  :before-upload="beforeUpload"
                  :file-list="fileList"
                  :headers="uploadHeaders"
                  multiple
                  :limit="maxUploadCount"
                  list-type="picture-card"
                  name="image"
                >
                  <i class="el-icon-plus"></i>
                </el-upload>
              </div>
            </el-form-item>
          </el-col>
        </el-row>
      </el-card>

      <div class="form-footer">
        <el-button type="primary" @click="submitForm">提交</el-button>
        <el-button @click="resetForm">重置</el-button>
      </div>
    </el-form>
  </div>
</template>

<script setup>
import { ref, getCurrentInstance, computed, onMounted } from 'vue';
import { submitProposal } from "@/api/ciinput/proposal";
import { getToken } from "@/utils/auth";
import { departments , employees } from '@/utils/proposalData';


const { proxy } = getCurrentInstance();

// 定义表单初始状态
const initialFormData = {
  status: '待审核',
  month: null,
  departmentName: '',
  proposerName: '',
  proposerId: '',
  proposalTime: null,
  proposalTypeName: '',
  title: '',
  categoryName: '',
  content: '',
  isCompanyPromoted: false,
  isFinancePromoted: false,
  isQualityPromoted: false,
  feasibilityDepartment: '',
  feasibilityResult: '',
  feasibilityTime: null,
  feasibilityOpinion: '',
  implementationDepartment: '',
  implementationStartTime: null,
  implementationEndTime: null,
  implementer1Name: '',
  implementer1EmployeeId: '',
  implementer2Name: '',
  implementer2EmployeeId: '',
  implementer3Name: '',
  implementer3EmployeeId: '',
  implementer4Name: '',
  implementer4EmployeeId: '',
  implementer5Name: '',
  implementer5EmployeeId: '',
  notes: '',
  image: null
};

const formData = ref({...initialFormData});

const employeesData = ref(employees);

const rules = ref({
  month: [{ required: true, message: "请选择月份", trigger: "change" }],
  departmentName: [{ required: true, message: "请输入部门", trigger: "blur" }],
  proposerName: [
    { required: true, message: "请输入提案人姓名", trigger: "blur" },
    { validator: validateEmployee, trigger: "blur" }
  ],
  proposerId: [
    { required: true, message: "请输入提案人ID", trigger: "blur" },
    { pattern: /^\d+$/, message: "请确认工号是否为数字", trigger: "blur" },
    { validator: validateEmployee, trigger: "blur" }
  ],
  proposalTime: [{ required: true, message: "请选择提案时间", trigger: "change" }],
  proposalTypeName: [{ required: true, message: "请选择提案类型A/B..", trigger: "change" }],
  title: [{ required: true, message: "请输入提案名称", trigger: "blur" }],
  categoryName: [{ required: true, message: "请选择提案类别,'成本'...", trigger: "change" }],
  implementer1Name: [
    { required: true, message: "请输入实施人员1姓名", trigger: "blur" },
    { validator: validateImplementer, trigger: "blur" }
  ],
  implementer1EmployeeId: [
    { required: true, message: "请输入实施人员1工号", trigger: "blur" },
    { pattern: /^\d+$/, message: "请确认工号是否为数字", trigger: "blur" },
    { validator: validateImplementer, trigger: "blur" }
  ],
  implementer2Name: [{ validator: validateImplementer, trigger: "blur" }],
  implementer2EmployeeId: [
    { pattern: /^\d+$/, message: "请确认工号是否为数字", trigger: "blur" },
    { validator: validateImplementer, trigger: "blur" }
  ],
  implementer3Name: [{ validator: validateImplementer, trigger: "blur" }],
  implementer3EmployeeId: [
    { pattern: /^\d+$/, message: "请确认工号是否为数字", trigger: "blur" },
    { validator: validateImplementer, trigger: "blur" }
  ],
  implementer4Name: [{ validator: validateImplementer, trigger: "blur" }],
  implementer4EmployeeId: [
    { pattern: /^\d+$/, message: "请确认工号是否为数字", trigger: "blur" },
    { validator: validateImplementer, trigger: "blur" }
  ],
  implementer5Name: [{ validator: validateImplementer, trigger: "blur" }],
  implementer5EmployeeId: [
    { pattern: /^\d+$/, message: "请确认工号是否为数字", trigger: "blur" },
    { validator: validateImplementer, trigger: "blur" }
  ]
});

// 提案人员的信息校验函数
function validateEmployee(rule, value, callback) {
  const name = formData.value.proposerName;
  const id = formData.value.proposerId;
  
  // 只有当姓名和工号都填写时才进行校验
  if (name && id) {
    const matchedEmployee = employeesData.value.find(emp => 
      emp.name === name && emp.id === id
    );
    
    if (!matchedEmployee) {
      callback(new Error('提案人姓名与工号不匹配'));
    } else {
      callback();
    }
  } else {
    // 如果其中一个未填写，则不进行校验
    callback();
  }
}

// 实施人员信息校验函数
function validateImplementer(rule, value, callback) {
  // 根据规则名称确定是校验第几个实施人员
  const field = rule.field;
  // 从字段名中提取索引，例如 implementer2Name -> 2
  const match = field.match(/implementer(\d+)(Name|EmployeeId)/);
  if (!match) {
    callback();
    return;
  }
  
  const index = match[1];
  
  const name = formData.value[`implementer${index}Name`];
  const id = formData.value[`implementer${index}EmployeeId`];
  
  // 如果姓名或工号任意一个填写了，则进行校验
  if (name || id) {
    // 如果其中一个为空，则报错
    if (!name) {
      callback(new Error(`实施人员${index}姓名不能为空`));
      return;
    }
    
    if (!id) {
      callback(new Error(`实施人员${index}工号不能为空`));
      return;
    }
    
    // 如果都填写了，则校验是否匹配
    const matchedEmployee = employees.find(emp => 
      emp.name === name && emp.id === id
    );
    
    if (!matchedEmployee) {
      callback(new Error(`实施人员${index}姓名与工号不匹配`));
    } else {
      callback();
    }
  } else {
    // 如果都没有填写，则不进行校验
    callback();
  }
}

const proposalTypes = ref([
  { type: 'A', label: 'A-成本' },
  { type: 'B', label: 'B-效率' },
  { type: 'C', label: 'C-质量' },
  { type: 'D', label: 'D-安全' },
  { type: 'E', label: 'E-能源' },
  { type: 'F', label: 'F-5S' },
  { type: 'G', label: 'G-设备有效性' },
  { type: 'H', label: 'H-人机工效' },
  { type: 'I', label: 'I-其他' }
]);



const filteredCategories = computed(() => {
  const type = formData.value.proposalTypeName;
  if (!type) return [];
  const categoryMap = {
    'A': ['成本'],
    'B': ['效率'],
    'C': ['质量'],
    'D': ['安全'],
    'E': ['能源'],
    'F': ['5S'],
    'G': ['设备有效性'],
    'H': ['人机工效'],
    'I': ['其他']
  };
  return categoryMap[type] || [];
});

function typeChange(value) {
  formData.value.categoryName = '';
}

const uploadUrl = ref('/dev-api/proposal/upload');
const maxUploadCount = 6;
const fileList = ref([]);
const uploadHeaders = ref({
  Authorization: "Bearer " + getToken()
});

function updateUploadHeaders() {
  const token = getToken();
  if (token) {
    uploadHeaders.value = {
      Authorization: "Bearer " + token
    };
  }else{
    console.log("没有访问令牌");
  }
}

function handleRemove(file, fileList) {
  // 更新文件列表
  fileList.value = fileList;
  
  // 更新formData中的image字段
  if (fileList.length > 0) {
    formData.value.image = fileList.map(f => f.response ? f.response.data.url : f.url).join(',');
  } else {
    formData.value.image = null;
  }
}

function beforeUpload(file) {
  updateUploadHeaders();
  const isJPG = file.type === 'image/jpeg' || file.type === 'image/png';
  const isLimit = file.size / 1024 / 1024 < 5;
  const isMaxLength = fileList.value.length < maxUploadCount;
  if (!isJPG) {
    proxy.$modal.msgError('上传图片只能是 JPG 或 PNG 格式!');
    return false;
  }
  if (!isLimit) {
    proxy.$modal.msgError('上传图片大小不能超过 5MB!');
    return false;
  }
  if (!isMaxLength) {
    proxy.$modal.msgError(`最多只能上传 ${maxUploadCount} 张图片!`);
    return false;
  }
  return true;
}

function handleUploadSuccess(response, file, fileList) {
  if (response.code === 200) {
    // 更新文件列表
    fileList.value = fileList;
    
    // 保存图片URL到formData中，以逗号分隔
    formData.value.image = fileList.value.map(f => f.response.data.url).join(',');
    
    proxy.$modal.msgSuccess("图片上传成功");
  } else {
    proxy.$modal.msgError("图片上传失败: " + response.msg);
  }
}

function handleUploadError(err, file, fileList) {
  console.error('图片上传失败:', err);
  console.error('失败的文件:', file);
  console.error('当前文件列表:', fileList);
  
  // 根据错误类型给出不同的提示
  if (err.status === 0) {
    proxy.$modal.msgError("图片上传失败: 网络连接问题或服务器无响应，请检查后端服务是否正常运行");
  } else if (err.status === 404) {
    proxy.$modal.msgError("图片上传失败: 上传接口不存在，请检查接口路径配置");
  } else if (err.status === 500) {
    proxy.$modal.msgError("图片上传失败: 服务器内部错误，请联系管理员");
  } else {
    proxy.$modal.msgError("图片上传失败: " + (err.message || "未知错误"));
  }
}

function resetForm() {
  // 重置表单数据
  formData.value = {...initialFormData};
  
  // 重置文件列表
  fileList.value = [];
  
  // 重新初始化上传头部
  updateUploadHeaders();
  
  // 重置表单验证
  proxy.$refs["formRef"].resetFields();
  
  proxy.$modal.msgSuccess("表单已重置");
}

function submitForm() {
  proxy.$refs["formRef"].validate(valid => {
    if (valid) {

      const submitData = {...formData.value};

      //展示提交数据
      //console.log('最终提交的数据:', submitData);
      //console.log('提交的图片数据:', submitData.image);


      submitProposal(formData.value).then(response => {
        proxy.$modal.msgSuccess("提交成功");
        // 提交成功后重置表单
        resetForm();
      }).catch((error) => {
        console.error('提交失败:', error);
        proxy.$modal.msgError("提交失败: " + (error.message || error));
      });
    } else {
      proxy.$modal.msgError("表单校验失败,请检查表单填写内容");
      return false;
    }
  });
}

onMounted(() => {
  updateUploadHeaders();
});
</script>

<style scoped>
.proposal-form {
  padding: 20px;
}

.mb-3 {
  margin-bottom: 15px;
}

.card-header {
  font-weight: bold;
  color: #333;
}

.section-title {
  font-weight: bold;
  margin: 15px 0 10px 0;
  color: #666;
}

.form-footer {
  text-align: center;
  padding: 20px 0;
}

:deep(.el-card__header) {
  padding: 10px 20px;
  background-color: #f5f7fa;
}

:deep(.el-form-item__label) {
  font-weight: normal;
}

:deep(.el-upload--picture-card) {
  width: 100px;
  height: 100px;
  line-height: 100px;
}

:deep(.el-upload-list--picture-card .el-upload-list__item) {
  width: 100px;
  height: 100px;
}
</style>